#include "HeartbeatController.h"
#include <QDebug>
#include <QElapsedTimer>
#include <QCoreApplication>

HeartbeatController::HeartbeatController(QThread *thread, QObject *parent)
    : QObject(parent), m_model(nullptr), m_isRunning(false), m_thread(thread)
{

}

void HeartbeatController::initialize()
{
    qDebug() << "HeartbeatController initialize" << QThread::currentThreadId();
    if (m_model == nullptr) {
        m_model = new FocusMachineModel();

        m_model->moveToThread(m_thread);

        qDebug() << "HeartbeatController initialized with FocusMachineModel";
    } else {
        qDebug() << "HeartbeatController already initialized";
    }
}

void HeartbeatController::startConnectToModbusServer(const QString &ip, int port)
{
    qDebug() << "Start connect to modbus server thread: " << QThread::currentThreadId();
    connectToModbusServer(ip, port);
    if (m_model && m_model->isConnected()) {
        emit modbusServerConnected();
        emit connectionStatusChanged(true);
    } else {
        emit connectionStatusChanged(false);
    }
}

void HeartbeatController::startDisconnectFromModbusServer()
{
    qDebug() << "Start disconnect from modbus server thread: " << QThread::currentThreadId();
    disconnectFromModbusServer();
    emit modbusServerDisconnected();
    emit connectionStatusChanged(false);
}

void HeartbeatController::startHeartbeat()
{
    if (m_model == nullptr) {
        qDebug() << "HeartbeatController not initialized";
        return;
    }

    m_isRunning = true;
    while (m_isRunning) {
        checkHeartbeat();
        MySleep(1000);
    }
}

void HeartbeatController::stopHeartbeat()
{
    m_isRunning = false;
    qDebug() << "Heartbeat stopped";
}

void HeartbeatController::checkHeartbeat()
{
    if (m_model == nullptr) {
        qDebug() << "FocusMachineModel not initialized";
        return;
    }

    qDebug() << "HeartbeatController checkHeartbeat" << QThread::currentThreadId();
    int16_t value;
    if (m_model->readModbusRegister(519, value)) {
        if (value == 1) {
            m_model->writeModbusRegister(519, 0);
            emit heartbeatDetected();
        } else {
            emit heartbeatMissed();
        }
    } else {
        qDebug() << "Failed to read heartbeat register";
        emit heartbeatMissed();
    }
}

void HeartbeatController::MySleep(uint32_t ms)
{
    QElapsedTimer t;
    t.start();
    while(t.elapsed() < ms)
    {
        QCoreApplication::processEvents();
    }
}

bool HeartbeatController::MySleep(uint32_t ms, bool *value)
{
    QElapsedTimer t;
    t.start();
    while(t.elapsed() < ms)
    {
        QCoreApplication::processEvents();

        if(*value == true)
        {
            return true;
        }
    }

    return false;
}

void HeartbeatController::connectToModbusServer(const QString &ip, int port)
{
    if (m_model) {
        m_model->setupModbusClient(ip, port);
        bool connected = m_model->connectToModbusServer();
        emit connectionStatusChanged(connected);
    } else {
        qDebug() << "FocusMachineModel not initialized";
        emit connectionStatusChanged(false);
    }
}

void HeartbeatController::disconnectFromModbusServer()
{
    if (m_model) {
        m_model->disconnectFromModbusServer();
        emit connectionStatusChanged(false);
    } else {
        qDebug() << "FocusMachineModel not initialized";
    }
}
